<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat, toYuan, copyToCliboard, timeFormat_2 } from '@/hooks/util'
import * as userListApi from '@/api/userList'
import { message } from 'ant-design-vue'
import ChongMoney from './components/ChongMoney.vue'
import Recharge from './components/Recharge.vue'

const route = useRoute()
const ChongMoneyRef = ref()
const rechargeRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper?: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true 
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  [propName: string]: any
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '用户信息',
    key: 'userName',
    width: 300,
  },
  {
    title: '余额',
    key: 'balance',
    width: 300,
  },
    {
    title: '推广积分',
    key: 'point',
    width: 300,
  },
  {
    title: '邀请人',
    key: 'shareUserName',
    width: 400,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    align: 'center',
  },
]

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await userListApi.userPageList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

onMounted(() => getList())

import type { SelectProps } from 'ant-design-vue'
const orderStatusList = ref<SelectProps['options']>([
  {
    label: '禁用',
    value: 0,
  },
  {
    label: '启用',
    value: 1,
  },
])
const userGroupList = ref<SelectProps['options']>([
  {
    label: 'ADMIN',
    value: 1,
  },
  {
    label: 'USER',
    value: 0,
  },
])

const formRef = ref()
interface FormState {
  userName?: string
  userGroup?: number
  status?: number
  [propName: string]: any
}
const formState = reactive<FormState>({})

// 查询
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.userName = formState.userName || ''

    if (formState.userGroup == 0 || formState.userGroup == 1) {
      searchParams.value.userGroup = formState.userGroup
    }

    if (formState.status == 0 || formState.status == 1) {
      searchParams.value.status = formState.status
    }
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.resetFields()
  for (let key in searchParams.value) {
    if (key != 'currentPage' && key != 'pageSize')
      searchParams.value.hasOwnProperty(key) && delete searchParams.value[key]
  }
  getList()
}

const chongMoney = (id: string) => {
  ChongMoneyRef.value.showModal(id)
}

// 复制规则
const copyRule = (record: any) => {
  copyToCliboard(`您的票达人账号：${record.userName}已充值，当前余额：${toYuan(record.balance)}元`)
  // message.success('复制成功')
}

const recharge = (id: string) => {
  console.log('充值')
  rechargeRef.value.showModal(id)
}
</script>

<template>
  <page-container :title="route.meta.title">
    <a-card style="overflow-x: scroll">
      <div class="searchBox">
        <a-form ref="formRef" layout="inline" :model="formState" class="formClass">
          <a-form-item label="用户名" name="userName">
            <a-input v-model:value="formState.userName" placeholder="用户名" />
          </a-form-item>

          <a-form-item label="用户组" name="userGroup">
            <!-- <a-input v-model:value="formState.userGroup" placeholder="用户组" /> -->
            <a-select v-model:value="formState.userGroup" placeholder="请选择" style="width: 150px" allowClear>
              <a-select-option v-for="(item, index) in userGroupList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="状态" name="status">
            <a-select v-model:value="formState.status" placeholder="状态" style="width: 150px" allowClear>
              <a-select-option v-for="(item, index) in orderStatusList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" style="border-radius: 6px" @click="search">搜索</a-button>
            <a-button @click="reset" style="border-radius: 6px">重置</a-button>
          </a-form-item>
        </a-form>
      </div>

      <a-table style="overflow-x: scroll" :columns="columns" :data-source="dataSource" :pagination="pagination"
        :loading="loading" @change="changePage" rowKey="id" size="small" :scroll="{ x: 100 }">
        <template #emptyText>
          <a-empty description="暂无数据" />
        </template>

        <template #headerCell="{ column }">
          <template v-if="column.key === 'id'">
            <span>id</span>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userName'">
            <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '140px' }">
              <a-descriptions-item label="用户名">{{ record.userName }}</a-descriptions-item>
              <a-descriptions-item label="用户组 / 状态">
                <a-tag color="blue">{{ record.userGroup }}</a-tag>
                <a-tag color="blue" v-if="record.enable == 1">启用</a-tag>
                <a-tag color="red" v-if="record.enable == 0">禁用</a-tag>
              </a-descriptions-item>
            </a-descriptions>
          </template>

          <template v-if="column.key === 'shareUserName'">
            <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '140px' }">
              <a-descriptions-item label="邀请人">
                {{ record.shareUserName || '无' }}
              </a-descriptions-item>
              <a-descriptions-item label="创建时间">
                {{ timeFormat_2(record.createTime) }}
              </a-descriptions-item>
            </a-descriptions>
          </template>

          <template v-else-if="column.key === 'balance'">
            <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
              <a-descriptions-item label="余额">
                ￥{{ toYuan(record.balance) }}
                <a>
                  <EditOutlined @click="chongMoney(record.id)" style="margin-left: 2px" />
                </a>
              </a-descriptions-item>
              <a-descriptions-item label="NB余额">￥{{ record.nbBalance }}</a-descriptions-item>
            </a-descriptions>
          </template>

          <template v-else-if="column.key === 'point'">
            <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
              <a-descriptions-item label="推广积分">
                {{ record.pointCard }}
              </a-descriptions-item>
            </a-descriptions>
          </template>

          <template v-else-if="column.key === 'action'">
            <div>
              <a @click="recharge(record.id)">充值</a>
              <a @click="copyRule(record)" style="margin-left: 15px">
                <CopyOutlined />
              </a>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
    <ChongMoney ref="ChongMoneyRef" @refresh="getList"></ChongMoney>
    <Recharge ref="rechargeRef" @refresh="getList"></Recharge>
  </page-container>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  width: 170px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.aTag-seatNo:nth-child(n + 2) {
  margin-top: 3px;
}
.formClass {
  :nth-child(1) {
    margin-bottom: 2px;
  }
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}

.imgBox {
  width: 50px;
  height: 50px;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 300px;
  img {
    width: 100%;
  }
}

.robitStatusClass {
  text-align: center;
}
</style>
